package com.common.util;

import org.springframework.util.ResourceUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 读取txt：生成序列号（prefix+date+num(3))
 * Created by wrl on 2017/10/23.
 */
public class SerquenceSomeUtil {
    private static String path = "D:/server/webapps/slbgscs/sequence.txt";
    private static File file;
    /** 步长 */
    private static long sequence = 1L;
    /** 前一个id */
    private static  long lastWorkID = 0;
    /** 生成的id */
    private static long newWorkID = 0;
    /** 读取第几行数据(OP:1  OB:2  SAO:3) */
    private static int lineNum = 1;
    /** 读写 */
    private static List<String> contentList = new ArrayList<>();
    /** 序列号类型： 订单号=OP/1，发货通知单=OB/2，出库单=SAO/3 */
    private static String prefix;

    private static void getLastWorkID(){

        if(0 != lastWorkID) {
            return;
        }

        //1.获取前一个id
        try {
            file = ResourceUtils.getFile(path);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            int index = 1;
            String content = null;
            while(index <= 3){
                String temp = null;
                if((temp = reader.readLine())!=null && !temp.equals("")) {
                    contentList.add(temp);
                } else {
                    contentList.add("19900101001");
                }
                if(index == lineNum) {
                    content = temp;
                }
                index++;
            }
            reader.close();
            if(null != content && !"".equals(content)) {
                lastWorkID = Long.parseLong(content);
            }
        }  catch (FileNotFoundException e) {
            e.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static synchronized String nextID(){
        judeFileExists(path);

        try{
            prefix = prefix.toUpperCase();
            if(!"OP".equals(prefix) && !"OB".equals(prefix) && !"SAO".equals(prefix)){
                throw new Exception("Please enter the correct serial number type!");
            }
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }

        //前缀:对应读取第几行
        switch (prefix){
            case "OP":   lineNum = 1;     break;
            case "OB":   lineNum = 2;     break;
            case "SAO":   lineNum = 3;     break;
        }

        //获取前一个id
        getLastWorkID();

        long date = 0;
        if(0 != lastWorkID){
            date = Long.parseLong((lastWorkID + "").substring(0, 8));
        }
        long timestamp = timeGen();
        if(date == timestamp) {
            //相同日期
            newWorkID = lastWorkID + sequence;
        }else{
            //不同日期
            newWorkID = Long.parseLong(timestamp +"0001");
        }
        lastWorkID = newWorkID;

        StringBuffer sb = new StringBuffer();
        for(int i = 0 ; i < 3; i++){
            if((lineNum-1)== i){
                contentList.set(i,newWorkID+"");
            }
            if(i<contentList.size()) {
                sb.append(contentList.get(i)+"\r\n");
            } else {
                sb.append("\r\n");
            }
        }

        //把新的id存入txt中
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(sb.toString());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prefix+newWorkID;
    }

    private static long sdf(long num){
        if(0 == num || -1 == num) {
            return num;
        }
        String numStr = new SimpleDateFormat("yyyyMMdd").format(num);
        return Long.parseLong(numStr);
    }

    /**
     * 程序入口
     * @param type 订单号=OP/1，发货通知单=OB/2，出库单=SAO/3
     */
    public static String exc(/*String filePath,*/String type){
        if(prefix != type){
            prefix = type;
            lastWorkID = 0;
            newWorkID = 0;
        }
//        path = filePath;
        return nextID();
    }

    private static long timeGen() {
        long timeMillis = sdf(System.currentTimeMillis());
        return timeMillis;
    }

    /**
     * 是否存在：不存在时创建
     * @param filePath
     */
    private static void judeFileExists(String filePath){
        file = new File(filePath);
        if(!file.exists()){
            File directory = new File(file.getParent());
            if(!directory.exists()) {
                directory.mkdirs();
            }
            try {
                file.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
